package j.todo;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;

public class DBAdapter {
	private final Context context;
	static final String DB = "memos.db";
	static final String TABLE = "lines";
	static final String C0L1 = "line";
	static final String C0L2 = "time";
	static final String C0L3 = "prior";
	static final String C0L4 = "calendar";
	static final int VERSION = 1;
	static final String CREATE = "create table " + TABLE
			+ "(_id integer primary key autoincrement, " + C0L1
			+ " text not null, " + C0L2 + " text, " + C0L3 + " text, "
			+ C0L4 + " text);";
	static final String DROP = "drop table ";
	private SQLiteDatabase db;
	private NoteOpenHelper dbHelper;

	public DBAdapter(Context ctx) {
		context = ctx;
	}

	public DBAdapter open() throws SQLException {
		dbHelper = new NoteOpenHelper(context);
		db = dbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		dbHelper.close();
	}

	public Cursor fetchAllMemo() {
		return db.query(TABLE, new String[] { BaseColumns._ID, C0L1, C0L2, C0L3 }, null,
				null, null, null, "_id DESC");
		// return db.rawQuery("select * from lines;", null);
	}

	public void addMemo(String memo,String time, String prior) {
		ContentValues Values = new ContentValues();
		Values.put(C0L1, memo);
		Values.put(C0L2, time);
		Values.put(C0L3, prior);
		
		long id = db.insert(TABLE, null, Values);
//		
////		db.execSQL("insert into lines(line) values('"+ memo +"');");
//		
////		if(id<0)
////			return "";
////		return Long.toString(id);

	}

	public void delMemo(String id) {
		db.delete(TABLE, "_id = ?", new String[] { id });
	}

	public void modMemo(String id, String memo) {
	}

	private class NoteOpenHelper extends SQLiteOpenHelper {

		public NoteOpenHelper(Context c) {
			super(c, DB, null, VERSION);
		}

		public void onCreate(SQLiteDatabase db) {
			db.execSQL(CREATE);
		}

		public void onUpgratde(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w("debug", "Version mismatch :" + oldVersion + " to "
					+ newVersion);
			db.execSQL(DROP + TABLE + ";");
			onCreate(db);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub

		}

	}
}
